package com.itheima.util;

import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;

public class AppJwtUtil {

    // TOKEN的有效期一天（S）
    private static final int TOKEN_TIME_OUT = 3_600;
    // 加密KEY
    private static final String TOKEN_ENCRY_KEY = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";
    // 最小刷新间隔(S)
    private static final int REFRESH_TIME = 300;
    // 获取token方法  userId 和 userName是要存到token的用户信息， 如有需要可以添加更多
    public static String getToken(Long userId){
        Map<String, Object> claimMaps = new HashMap<>();
        claimMaps.put("id",userId);
        long currentTime = System.currentTimeMillis();
        return Jwts.builder()
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date(currentTime))  //签发时间
                .setSubject("system")  //说明
                .setIssuer("heima") //签发者信息
                .setAudience("app")  //接收用户
                .compressWith(CompressionCodecs.GZIP)  //数据压缩方式
                .signWith(SignatureAlgorithm.HS512, generalKey()) //加密方式
                .setExpiration(new Date(currentTime + TOKEN_TIME_OUT * 1000))  //过期时间戳
                .addClaims(claimMaps) //cla信息
                .compact();
    }
    /**
     * 获取token中的claims信息
     *
     * @param token
     * @return
     */
    private static Jws<Claims> getJws(String token) {
            return Jwts.parser()
                    .setSigningKey(generalKey())
                    .parseClaimsJws(token);
    }
    /**
     * 获取payload body信息
     * @param token
     * @return
     */
    public static Claims getClaimsBody(String token) {
        try {
            return getJws(token).getBody();
        }catch (ExpiredJwtException e){
            return null;
        }
    }

    /**
     * 获取hearder body信息
     *
     * @param token
     * @return
     */
    public static JwsHeader getHeaderBody(String token) {
        return getJws(token).getHeader();
    }

    /**
     * 检查失败会报错
     * 检查token
     */
    public static Claims checkToken(String token) {
        try {
            Claims claims = getClaimsBody(token);
            if(claims==null){
               throw new RuntimeException("token解析失败");
            }
            return claims;
        } catch (ExpiredJwtException ex) {
            throw new RuntimeException("token已经失效");
        }catch (Exception e){
            throw new RuntimeException("token解析失败");
        }
    }

    /**
     * 由字符串生成加密key
     *
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getEncoder().encode(TOKEN_ENCRY_KEY.getBytes());
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    public static void main(String[] args) {
//        String token = getToken(1);
//        System.out.println(token);
        Claims claims = checkToken("AAAAAAAADWLwQnDMAwAd9E7BsuJXTcbdAzJEcSBgKlsaCndvcqjvzuO-8DRK6ywzbfiM5IL2Ue3cC6OM0eXGIULesmJYYJKHVZMGPHu0xwm0MF261u7nFdXNd2lnmRGYzOj1ozl1f7nEq5zqDwf1vH7A-lS_B2EAAAA.X6NKSbKeQsZfkGOsqmJu22nLdxlWHD9mCIj8DKdLN9idsVifDb8WbWbufJIeQFwlfBr5_OPifQFKmLAyEPagvQ");
        Object id = claims.get("userId");
        System.out.println(id);
    }
}
